<template>
    <div class="index">
        <el-form 
        class="loginForm"
        >
            <p>十方智育后台管理系统</p>

            <el-form-item 
            required>
                <el-input 
                class="usernameInp"
                v-model="usernameInput" 
                placeholder="用户名" 
                clearable>
                <template #prefix>
                    <el-icon><UserFilled /></el-icon>
                </template>
                </el-input>
            </el-form-item>

            <el-form-item 
            required>
                <el-input 
                class="passwordInp"
                v-model="passwordInput"
                type="password"
                placeholder="密码"
                show-password
                clearable>
                <template #prefix>
                    <el-icon><Lock /></el-icon>
                </template>
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-input
                class="checkCodeInp"
                v-model="checkcode"
                type="text"
                placeholder="验证码"
                clearable>
                    <template #prefix>
                    <el-icon><CircleCheck /></el-icon>
                    </template>
                </el-input>
                <img :src="imgCode" @click="getCode()" style="width: 100px; height: 35px; margin: 0 0 0 20px;position:relative;left: 5px" alt="" />
            </el-form-item>
            <el-checkbox
            class="repass"
            v-model="checked"
            >
            记住密码
            </el-checkbox><br>
            <el-button @click="toIndex()" class="but" type="primary">登录</el-button>
            <el-button class="but" type="success" @click="toRegister()">
                注册
            </el-button>

        </el-form>
    </div>

    <el-dialog 
      v-model="addFormVisible" 
      title="注册" 
      width="500"
      @close="cancel"
      >
      <el-form :model="loginInfor">
        <el-form-item label="用户名称">
            <el-input v-model="loginInfor.username" placeholder="输入用户名称" autocomplete="off" @blur="checkUsername()" />
        </el-form-item>
        <el-form-item label="用户密码">
            <el-input v-model="loginInfor.password" placeholder="输入用户密码" autocomplete="off" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="loginInfor.nickName" placeholder="输入昵称" style="margin-left: 30px;"  autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱">
            <el-input v-model="loginInfor.email" placeholder="输入邮箱" style="margin-left: 30px;" autocomplete="off" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="loginInfor.phone" placeholder="输入手机号" style="margin-left: 15px;" autocomplete="off" />
        </el-form-item>
        <el-form-item label="图片" :label-width="formLabelWidth">
            <el-upload
              style="margin-left: 30px;"
              v-model:file-list="fileList"
              class="avatar-uploader"
              list-type="picture-card"
              action="http://localhost/file/upload"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="!fileList" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item label="角色">
            <el-select v-model="loginInfor.role" placeholder="请选择" style="margin-left: 30px; width: 100px;">
              <el-option label="管理员" value="1" />
              <el-option label="咨询师" value="2" />
              <el-option label="客服" value="3" />
            </el-select>
        </el-form-item>
        <el-form-item label="咨询师id">
            <!-- {{ loginInfor.role==1 }} -->
            <el-input v-model="loginInfor.cid" placeholder="输入id" style="margin-left: 5px; width: 150px;" autocomplete="off" :disabled="loginInfor.role!=2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel2()">取消</el-button>
          <el-button type="primary"
          :disabled="registerInf"
          @click="register()">
            注册
          </el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
const usernameInput = ref('硕大的根')
const passwordInput = ref('123456')
const checkcode = ref('')
const checked = ref(false)
const registerInf = ref(true)

const url = ref("http://localhost/file/downLoad?fileName=");
const fileList = ref([]);
const imageUrl=ref('');
const delUrl=ref('');


// 页面加载时，获取验证码
onMounted(() => {
  getCode();
})

const imgCode = ref(''); // 图片验证码
const answer = ref(''); // 验证码答案
let timerId; // 声明一个变量来存储定时器的ID
// 获取后端验证码信息
const getCode = () => {
  // 清除之前的定时器
  if (timerId) {
    clearTimeout(timerId);
  }
  // 发送请求
  axios.get('/captcha')
  .then((res) => {
    const result = res.data;
    if(result.code == 1){
      imgCode.value = "data:image/gif;base64," + result.data.img;
      answer.value = result.data.answer;
      // 调用定时器方法
      timer();
    }
  })
}

function checkUsername() {
  axios.get('/us/findByUn', {
    params: {
      username: loginInfor.value.username
    }
  })
  .then((res) => {
    const result = res.data;
    if (result.code == 1) {
      ElMessage({
        message: '用户名已存在！',
        type: 'warning',
      })
      loginInfor.value.username = '';
    }
  })
}

// 定时器方法，定时2分钟后，销毁answer数据
const timer = () => {
  timerId = setTimeout(() => {
    answer.value = '';
  }, 120000);
}

const handleAvatarSuccess = (response,
uploadFile)  => {

  imageUrl.value = URL.createObjectURL(uploadFile.raw);

  delUrl.value = response.data;
  loginInfor.value.img = response.data;

}

function delImgInPan(){
    console.log(delUrl.value);
    axios.delete('http://localhost/file/delete',{params: {fileName: delUrl.value}})
}
function cancel() {
    addFormVisible.value=false;
    registerInf.value=true;
  }

function cancel2() {
    delImgInPan();
    addFormVisible.value=false;
  }


const router=useRouter()
const addFormVisible = ref(false);
const loginInfor = ref({
    id: '',
    username: '',
    password: '',
    nickName: '',
    email: '',
    phone: '',
    img: '',
    role: '',
    cid: 0,
    token: ''
})

function toRegister() {
    loginInfor.value = {
        id: '',
        username: '',
        password: '',
        nickName: '',
        email: '',
        phone: '',
        img: '',
        role: '',
        cid: 0,
        token: ''
    }

    addFormVisible.value = !addFormVisible.value;
    registerInf.value = !registerInf.value;

    //console.log(registerInf.value);
    

}

function register() {
  
  registerInf.value = !registerInf.value;
    

    //console.log(loginInfor.value);
    axios.post('/us/register',loginInfor.value) 
    .then(resp=>{
        //console.log(resp.data);
        let result = resp.data;
        if(result.code==1){
            ElMessage({
                message: '注册成功',
                type: 'success',
            })
            toRegister()  
        }
    })
}

function toIndex() {
    //console.log(loginInfor.value);


    // 验证验证码
    if(checkcode.value != answer.value){
            ElMessage({
            message: '验证码错误！',
            type: 'warning',
            })
            getCode();
            return;
    }

    loginInfor.value = {
        username: usernameInput.value,
        password: passwordInput.value,
    }
    
    axios.post('/us/loginSu',loginInfor.value)
    .then((res)=>{
        console.log(res.data); 
        let result =  res.data; 
        console.log(result.code);
        
        if(result.code==1){
            console.log(result.data);
            loginInfor.value = result.data;
            sessionStorage.setItem('loginInfor',JSON.stringify(loginInfor.value));
            //console.log(sessionStorage.getItem('loginInfor'));
            
            ElMessage({
                message: '登陆成功',
                type: 'success',
                })
                router.push('/homepage/home');
        }else{
            ElMessage({
            message: '用户名或密码错误！',
            type: 'error',
            })
            getCode();
        }
    })
   
}


</script>

<style scoped>
.index{position: absolute; width: 100%; height: 100%; background-image: url(/img/bg.jpg); background-size: cover; background-repeat: no-repeat; display: flex; justify-content: center; align-items: center;}
.loginForm{width: 455px; background-color: #fff; border-radius: 5px; text-align: center; padding: 20px;}
p{font-size: 20px; color: #78819e;}
.usernameInp{width: 390px; height: 45px; margin-top: 20px; margin-left: 30px;}
.passwordInp{width: 390px; height: 45px; margin: 20px 0 20px 30px;}
.checkCodeInp{width: 220px; height: 45px; margin-left: 30px;}
img{height: 45px; margin-left: 40px;}
.repass{margin-left: -308px;}
.but{width: 150px; height: 35px; margin-top: 20px;}
</style>